//
//  UITextField+L_TextField.m
//  WeCommunity
//
//  Created by mac on 2017/7/11.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "UITextField+L_TextField.h"
#import <objc/runtime.h>

@implementation UITextField (L_TextField)


+(void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
//        id obj = [[self alloc] init];
//        [obj swizzleMethod:@selector(addObject:)
//                withMethod:@selector(safeAddObject:)
//          isInstanceMethod:YES];
        
    });
}

-(void)inputTextMaxLength:(NSInteger)maxLength
{
    @weakify(self);
    [self.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        @strongify(self);
        
        UITextRange *selectedRange = [self markedTextRange];
        //获取高亮部分
        UITextPosition *pos = [self positionFromPosition:selectedRange.start offset:0];
        //如果在变化中是高亮部分在变，就不要计算字符了
        if (selectedRange && pos) {
            return;
        }
        NSString  *nsTextContent = self.text;
        NSInteger existTextNum = nsTextContent.length;
        if (existTextNum > maxLength)
        {
            //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
            [self setText:[nsTextContent substringToIndex:maxLength]];
        }
    }];
}

-(void)setTextFieldLeftView:(CGSize)size
                       font:(UIFont *)font
                  textColor:(UIColor *)textColor
                       text:(NSString *)text
{
    UILabel * leftView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,size.width, size.height)];
    leftView.font = font;
    leftView.textColor = textColor;
    leftView.text = text;
    
    self.leftView = leftView;
    self.leftView.bounds = leftView.bounds;
    self.leftViewMode = UITextFieldViewModeAlways;
}

//runtime 交换方法

- (void)swizzleMethod:(SEL)origSelector
           withMethod:(SEL)newSelector
     isInstanceMethod:(BOOL)isInstance
{
    Class cls = [self class];
    
    Method originalMethod;
    Method exchangeMethod;
    if (isInstance) {
        originalMethod = class_getInstanceMethod(cls, origSelector);
        exchangeMethod = class_getInstanceMethod(cls, newSelector);
    }else{
        originalMethod = class_getClassMethod(cls, origSelector);
        exchangeMethod = class_getClassMethod(cls, newSelector);
    }
    
    BOOL didAddMethod = class_addMethod(cls,
                                        origSelector,
                                        method_getImplementation(exchangeMethod),
                                        method_getTypeEncoding(exchangeMethod));
    if (didAddMethod) {
        class_replaceMethod(cls,
                            newSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, exchangeMethod);
    }
}

@end
